<?php
	/**
	 * Elgg product - add action
	 * 
	 * @package Elgg SocialCommerce
	 * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
	 * @author Cubet Technologies
	 * @copyright Cubet Technologies 2009-2010
	 * @link http://elgghub.com/
	 **/



	global $CONFIG;
	
	// Get variables
	//Depricated function replace
	$options = array(
		'types'					=>	"object",
		'subtypes'				=>	"stores",
		'limit'					=>	15,
		'count'					=>	TRUE,
	);
	
	$All_Store_Entities = elgg_get_entities($options);
	/*$All_Store_Entities = get_entities($type = "object", 
	  $subtype = "stores", 
	  $owner_guid = 0, 
	  $order_by = "", 
	  $limit = 15, 
	  $offset = 0, 
	  $count = true, 
	  $site_guid = 0, 
	  $container_guid = null, 
	  $timelower = 0, 
	  $timeupper = 0);*/
	
	$title_image = get_input("image_title");
	
	$title = trim(get_input("storestitle"));	
//	$file_name = trim($_FILES['upload']['name']);
	$desc = trim(get_input("storesbody"));
	$category = get_input("storescategory");
//	$product_type_id = get_input("product_type_id");
//	$tags = trim(get_input("storestags"));
	$access_id = (int) get_input("access_id");
	$date_from = get_input("date_from");
	$date_until = get_input("date_until");
	$units = get_input("units");
	$container_guid = (int) get_input('container_guid', 0);
//	$tax_country = trim(get_input("tax_country"));
	$error_field = "";
	$Max_Limit =0;

//  limit to be omitted later for now just increased to large number	
	if($All_Store_Entities>9999)
	{
		$Max_Limit = 1;
		$error_field .=",error";
		register_error(sprintf(elgg_echo("This version only to allow 10 products"),$error_field));
		$redirect = $CONFIG->wwwroot . "mod/{$CONFIG->pluginname}/add.php";
	}else{
	
		if (!$container_guid){
			$container_guid = $_SESSION['user']->getGUID();
		}
		
		// product fields hardcoded in start.php
		// later to detect the corect number programmaticly
		$product_fields = $CONFIG->product_fields[2];  
		
		
		//Validation
		if(empty($title)){
			$error_field .= ", ".elgg_echo("title");
		}
		if(empty($desc)){
			$error_field .= ", ".elgg_echo("stores:text");
		}
		if(empty($category)){
			$error_field .= ", ".elgg_echo("category");
		}
	
		//if(empty($product_type_id) || $product_type_id <= 0){
		//	$error_field .= ", ".elgg_echo("product:type");
		//}
		
		if (is_array($product_fields) && sizeof($product_fields) > 0){
			foreach ($product_fields as $shortname => $valtype){
				if($valtype['mandatory'] == 1){
					$value = trim(get_input($shortname));
					if($valtype['field'] == 'file')
						$value = trim($_FILES[$shortname]['name']);
					if(empty($value)){
						if($valtype['field'] == 'file' && $shortname == 'upload'){
							if($stores->mimetype == "")
								$error_field .= ", ".elgg_echo("product:".$shortname);
						}else{
							$error_field .= ", ".elgg_echo("product:".$shortname);
						}
					}else{
						if($shortname == 'quantity'){
							if(ereg("[^0-9]",$value))
								$error_field .= ", ".elgg_echo("product:".$shortname);
						}
						if($shortname == 'base_stock'){
							if(ereg("[^0-9]",$value))
								$error_field .= ", ".elgg_echo("product:".$shortname);
						}
						if($shortname == 'price'){
							if((!is_numeric($value)) || $value == 0 )
								$error_field .= ", ".elgg_echo("product:".$shortname);
						}
					}
				}
			}
		}
		
		if(!empty($error_field)){
			unset($_SESSION['product']);
			$_SESSION['product']['storestitle'] = $title;
			$_SESSION['product']['product_type_id'] = $product_type_id;
			$_SESSION['product']['storescategory'] = $category;
			$_SESSION['product']['storesbody'] = $desc;
			$_SESSION['product']['storestags'] = $tags;
			$_SESSION['product']['access_id'] = $access_id;
			$_SESSION['product']['price'] = $price;
			
			if (is_array($product_fields) && sizeof($product_fields) > 0){
				foreach ($product_fields as $shortname => $valtype){
					if($valtype['field'] != 'file')
						$_SESSION['product'][$shortname] = get_input($shortname);
				}
			}
			
			$error_field = substr($error_field,2);
	
			if($Max_Limit > 0){
				register_error(sprintf(elgg_echo("This version only to allow 10 products"),$error_field));
			}else{
				register_error(sprintf(elgg_echo("product:validation:null"),$error_field));
			}
			$container_user = get_entity($container_guid);
			$redirect = $CONFIG->wwwroot . "mod/{$CONFIG->pluginname}/add.php";
		}else{
			// Extract stores from, save to default stores (for now)
			$stores = new ElggObject();
			$stores->subtype="stores";
			$stores->access_id = $access_id;
			
			if (is_array($product_fields) && sizeof($product_fields) > 0){
				foreach ($product_fields as $shortname => $valtype){
					/*
					if($valtype['field'] == 'file' && $shortname == 'upload' && isset($_FILES[$shortname]) && $_FILES[$shortname]['name'] != ""){
						$prefix = "{$CONFIG->pluginname}/";
						$upload_file = new ElggFile();
						$filestorename = strtolower(time().$_FILES[$shortname]['name']);
						$upload_file->setFilename($prefix.$filestorename);
						$upload_file->setMimeType($_FILES[$shortname]['type']);
						$upload_file->originalfilename = $_FILES[$shortname]['name'];
						$upload_file->open("write");
						$upload_file->write(get_uploaded_file('upload'));
						$upload_file->close();
						
						$stores->filename = $upload_file->filename;
						$stores->mimetype = $upload_file->mimetype;
						$stores->originalfilename = $upload_file->originalfilename;
						$stores->simpletype = get_general_product_type($_FILES[$shortname]['type']);
					}*/
					$value = trim(get_input($shortname));
					if(!empty($value))
						$stores->$shortname = trim(get_input($shortname));
				}
			}
			$stores->title = $title;
			$stores->status = 1;
			$stores->description = $desc;
			//$stores->product_type_id = $product_type_id;
			$stores->category = $category;
			$stores->countrycode = $tax_country;
			$stores->date_from = $date_from;
			$stores->date_until = $date_until;
			//$stores->price = $price;
			$stores->units = $units;
			
			// Save tags
			$tags = explode(",", $tags);
			$stores->tags = $tags;
			
			
			if ($container_guid){
				$stores->container_guid = $container_guid;
			}
	
			
			
			//image stuff
			//$images = New ElggObject();
			$files = array();
		    $x = 0;
		    
		    foreach ($_FILES as $key => $value) {
		        if ((!is_null($value)) && ($value !== "")) {
		            $files[$x] = $value;
		            $x++;
					//echo " value is ".$files[$x].", ";
		        }
		    }
		    
		    $num_files = count($files[0]['tmp_name']);
		    
		    $result = $stores->save();
		  
			
			if ($result){
				if(in_array('product_add',$CONFIG->river_settings))
					add_to_river('river/object/stores/create','create',$_SESSION['user']->guid,$stores->guid);
				

				$images = array();
				 for ($i = 0; $i < $num_files - 1; $i++) {
			        // Shorten variable names
			        if($i==($title_image-1)){
			        	$order = "1";
			        }
			        else{
			        	$order = "2";
			        }
			        
			        $temp_file = $files[0]['tmp_name'][$i];
			        $filename = $files[0]['name'][$i];
				     
					$name = $files[0]['name'][$i];
   			 
					$image_ind = $i + 1;
					$image_prefix = $CONFIG->pluginname."/".$result."/".$image_ind;
					
					$new_image = array('path' => "$image_ind", 'order' => "$order");
					$images[] = $new_image;
					
					$product_imagehandler = new ElggFile();
					$product_imagehandler->owner_guid = $stores->owner_guid;
					$product_imagehandler->setFilename($image_prefix . ".jpg");
					$product_imagehandler->open("write");
					$product_imagehandler->write(file_get_contents($temp_file));
					$product_imagehandler->close();
					
					//$product_thumbtiny = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),25,25, true);
					$product_thumbsmall = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),40,40, true);
					$product_thumbmedium = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),190,130, false);
					$product_thumblarge = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),350,800, false);
					if ($product_thumbsmall) {
						
						$product_thumb = new ElggFile();
						$product_thumb->owner_guid = $stores->owner_guid;
						$product_thumb->setMimeType('image/jpeg');
						

						
						$product_thumb->setFilename($image_prefix."small.jpg");
						$product_thumb->open("write");
						$product_thumb->write($product_thumbsmall);
						$product_thumb->close();
						
						$product_thumb->setFilename($image_prefix."medium.jpg");
						$product_thumb->open("write");
						$product_thumb->write($product_thumbmedium);
						$product_thumb->close();
						
						$product_thumb->setFilename($image_prefix."large.jpg");
						$product_thumb->open("write");
						$product_thumb->write($product_thumblarge);
						$product_thumb->close();
						
						$image = $image_prefix.".jpg";
						$delfile = new ElggFile();
						$delfile->owner_guid = $owner;
						$delfile->setFilename($image);
						$delfile->delete();
										
					}
				 }
				 
				$stores->images = serialize($images);
				$stores->icontime = time();
				$stored = $stores->save();
			
			}
				
			if ($stored){
				system_message(elgg_echo("stores:saved"));
				unset($_SESSION['product']);
			}else{
				register_error(elgg_echo("stores:uploadfailed"));
			}
			$container_user = get_entity($container_guid);
			$redirect = $CONFIG->wwwroot . "pg/{$CONFIG->pluginname}/" . $container_user->username;
		}
		
	}
	forward($redirect);

?>
